--[[
Author: wangxiaoyan
Date: 2020-10-23 17:27:37
LastEditTime: 2020-11-14 20:43:27
FilePath: \Lua\View\CharactorUI\UICharactorInfoHeroBreak.lua
--]]

require 'View/UIBase/UIBase'
require "View/CharactorUI/UICharactorInfoHeroDetail"
require "View/CharactorUI/UICharactorInfoResBrek"

UICharactorInfoHeroBreak = UIBase.New(PanelNames.UICharactorInfoHeroBreak)
local _M = UICharactorInfoHeroBreak

_M.hasAddRedDots = false;

_M.ATLAS = "ui://CharactorUI/"

function _M.Init(PartnerId,func, isShowOneHero)
    _M.hero = logicMgr.HeroManager.getHeroDatabyPartnerId(tostring(PartnerId))
    _M.goFunc = func;
    _M.isShowOneHero = isShowOneHero;
    UIBase.Init(_M)
end

function _M:OnCreate()
    self.stateController = self:GetController("state")
    self.detailView = self:CreateComponent(UICharactorInfoHeroDetail,self:GetChild("preview"),self)
    self.resBrekView = self:CreateComponent(UICharactorInfoResBrek,self:GetChild("breakTip"),self)
    self.breakCost = self:GetChild("breakCost")
    self.redbreakCost1 = self:GetChild("redbreakCost1")
    self.redbreakCost2 = self:GetChild("redbreakCost2")
    self.breakFrame1 = self:GetChild("break1/frame")
    self.breakIcon1 = self:GetChild("break1/icon")
    self.breakNumIcon1 = self:GetChild("break1/numIcon")
    self.break1Controller_jinjie = self:GetController("jinjie",self:GetChild("break1"));
    self.break1Contrller_max = self:GetController("LR",self:GetChild("break1"));
    self.breakFrame2 = self:GetChild("break2/frame")
    self.breakIcon2 = self:GetChild("break2/icon")
    self.break2Controller_jinjie = self:GetController("jinjie",self:GetChild("break2"));
    self.break2Contrller_max = self:GetController("LR",self:GetChild("break2"));
    self.breakNumIcon2 = self:GetChild("break2/numIcon")
    self.breakMaxFrame = self:GetChild("maxStar/frame")
    self.breakMaxIcon = self:GetChild("maxStar/icon")
    self.breakMaxNumIcon = self:GetChild("maxStar/numIcon")
    self.maxStar_Controller_jinjie = self:GetController("jinjie",self:GetChild("maxStar"));
    self.maxStar_Controller_lr = self:GetController("LR",self:GetChild("maxStar"));
    self.showTipCtrl = self:GetController("ifShowTips")
    self.showTipCtrl.selectedIndex = 1
    --self.ctrlSpine = self:GetChild("Spine_Break")
    self:SetCtrlSipne(false)
    self.btnFetterHero = self:GetChild("BtnFetter")
    self.btnFetterAward = self:GetChild("BtnReward")
    self.btnFetterAttr = self:GetChild("BtnBonus")
    self.btnFetterHero.title = getLanguage("Trammel_Btn");
    self.btnFetterAward.title = getLanguage("TrammelPointReward_Btn");
    self.btnFetterAttr.title = getLanguage("TrammelBonus_Btn");
    self.breakbtn = self:GetChild("breakBtn")
    self.btnJump = self:GetChild("btnJump")
    self.btnSource = self:GetChild("btnSource")
    self.btnShop = self:GetChild("ShopBtn");
    self.effectController = self:GetController("effect", self.btnSource);
    self.sourceUIobj = self:GetChild("UISourceMultiple");
    self.showSourceController = self:GetController("showSource")
    --self.breakLvTip = self:GetChild("tips")
    self.breakLvCtrl = self:GetController("tips")
    self.isShowOneController = self:GetController("isShowOne")
    self.breakBars={}
    for i=2,5 do
        table.insert(self.breakBars,self:GetChild("bar"..i))
    end
    table.insert(self.breakBars,self:GetChild("bar7"))
    table.insert(self.breakBars,self:GetChild("bar9"))
    self.qualityBreakCtrl=self:GetController("qualityBreak")
    self.bpCtrl=self:GetController("breakPoint")
    self.breakPointCtrls={}
    self.bpEfts={}
    for i=1,9 do
        local bp=self:GetChild("breakPoint"..i)
        table.insert(self.breakPointCtrls,bp:GetController("state"))
        table.insert(self.bpEfts,bp:GetChild("effect_jblq"))
    end
    if self.isShowOneHero then
        self.isShowOneController.selectedIndex = 1;
    else
        self.isShowOneController.selectedIndex = 0;
    end
    self:InitAttr()
    self:refreshShop();
    self:RegisterOnClick(self.breakbtn,self.OnClickSendBreak)
    self:RegisterOnClick(self.btnJump,self.onClickSource)
    self:RegisterOnClick(self.btnSource,self.onClickSource)
    self:RegisterOnClick(self.btnShop,self.onClickShop)
    self:RegisterOnClick(self:GetChild("GoBtn"),self.OnClickSendBreak)
    self:RegisterOnClick(self:GetChild("clickBreakDetail"),self.OnClickDetail)

    self:RegisterOnClick(self.btnFetterHero, self.OnClickFetterHero)
    self:RegisterOnClick(self.btnFetterAward, self.OnClickFetterAward)
    self:RegisterOnClick(self.btnFetterAttr, self.OnClickFetterAttr)

    self:RegisterEvent(Config.EventType.Fresh_Star,self.RereshStarMsg)
    -- 监听道具数量变化事件。魂石数量变化时，更新界面数量
    self:RegisterEvent(Config.EventType.Fresh_Bag,self.OnItemChanged)
    self:RegisterEvent(Config.EventType.Fresh_BagUseItemBack,logicMgr.ItemManager.showGetItem)
end
function _M:InitAttr()
    self.attrHPSp = self:GetChild("attr0/icon")
    self.attrHP = self:GetChild("attr0/num")
    self.attrHPCtrl=self:GetChild("attr0"):GetController("c1")
    self.attrHPUP = self:GetChild("attr0/upNum")
    self.attrACKSp = self:GetChild("attr1/icon")
    self.attrACK = self:GetChild("attr1/num")
    self.attrACKCtrl=self:GetChild("attr1"):GetController("c1")

    self.attrACKUP = self:GetChild("attr1/upNum")
    self.attrDEFSp = self:GetChild("attr2/icon")
    self.attrDEF = self:GetChild("attr2/num")
    self.attrDEFCtrl=self:GetChild("attr2"):GetController("c1")

    self.attrDEFUP = self:GetChild("attr2/upNum")
    self.lvTipIcon = self:GetChild("attr3/icon")
    self.lvTip= self:GetChild("attr3/num")
    self.attrLvCtrl=self:GetChild("attr3"):GetController("c1")

    self.lvTipUP = self:GetChild("attr3/upNum")
    --self.qualityFrame = self:GetChild("break2/frame")
    --self.qualityIcon = self:GetChild("break2/icon")
    --self.qualityNumIcon = self:GetChild("break2/numIcon")
    --self.staegeController = self:GetController("jinjie",self:GetChild("break2"))
    --self.maxController = self:GetController("LR",self:GetChild("break2"))
    --self.qualityFrame_2 = self:GetChild("break1/frame")
    --self.qualityIcon_2 = self:GetChild("break1/icon")
    --self.qualityNumIcon_2 = self:GetChild("break1/numIcon")
    --self.staegeController_2 = self:GetController("jinjie",self:GetChild("break1"))
    --self.maxController_2 = self:GetController("LR",self:GetChild("break1"))
end
function _M:UpdateAttr()
    local function getCfg(id)
        local lastID=550150
        local info=dataTable.getRow("t_herorank", id)
        if table.getn(info)==0 then
            info=dataTable.getRow("t_herorank", lastID)
        end
        return info
    end
    local addAttr = G.dataTable["t_levelupaddattribute"][self.hero.star][toNumber(self.hero["partnerModelId"])]
    self.hero = logicMgr.HeroManager.getHeroDatabyPartnerId(tostring(self.hero.partnerId))

    local cfgId_2 = toNumber(self.hero["partnerModelId"]) * 1000 + self.hero.star
    local cfgInfo_2 = getCfg(cfgId_2)
    local cfgID = cfgInfo_2.f_HeroStarNext
    local cfgInfo = getCfg(cfgID)
    self.breakLvCtrl.selectedIndex = 0
    local function SetCtrl(a,b,ctrl)
        if tonumber(a)==tonumber(b) then
            ctrl.selectedIndex=1
        else
            ctrl.selectedIndex=0
        end
    end

    self.lvTipIcon.url =  "ui://CharactorUI/hero_attr_icon_dj"
    self.lvTip.text = string.format(getLanguage("HeroTips1"),cfgInfo_2.f_LevelCap)
    self.lvTipUP.text = string.format(getLanguage("HeroTips1"),cfgInfo.f_LevelCap)
    SetCtrl(cfgInfo_2.f_LevelCap,cfgInfo.f_LevelCap,self.attrLvCtrl)
    self:SetIcon(self.attrHPSp,"attr"..EnumConst.FighterAttributeEnum.HP,EnumConst.ItemShowType.ICON)
    self:SetIcon(self.attrACKSp,"attr"..EnumConst.FighterAttributeEnum.ATK,EnumConst.ItemShowType.ICON)
    self:SetIcon(self.attrDEFSp,"attr"..EnumConst.FighterAttributeEnum.DEF,EnumConst.ItemShowType.ICON)
    local baseData = clone(self.hero)
    logicMgr.HeroManager.processHeroBaseAttr(baseData,self.hero.level,self.hero.star)
    local attbase = baseData.allAttribute[EnumConst.AttributeTypeEnum.BASE]
    self.attrHP.text = attbase[EnumConst.FighterAttributeEnum.HP] + addAttr.f_Attribute1[3][2]*self.hero.level +addAttr.f_Attribute2[3][2]
    self.attrACK.text = attbase[EnumConst.FighterAttributeEnum.ATK] + addAttr.f_Attribute1[1][2]*self.hero.level +addAttr.f_Attribute2[1][2]
    self.attrDEF.text = attbase[EnumConst.FighterAttributeEnum.DEF] +addAttr.f_Attribute1[2][2]*self.hero.level +addAttr.f_Attribute2[2][2]
    local upAddAttr = G.dataTable["t_levelupaddattribute"][cfgInfo.f_HeroStar][toNumber(self.hero["partnerModelId"])]
    logicMgr.HeroManager.processHeroBaseAttr(baseData,self.hero.level,cfgInfo.f_HeroStar)
    local attup = baseData.allAttribute[EnumConst.AttributeTypeEnum.BASE]
    self.attrHPUP.text = attup[EnumConst.FighterAttributeEnum.HP] + upAddAttr.f_Attribute1[3][2]*self.hero.level +upAddAttr.f_Attribute2[3][2]
    SetCtrl(attbase[EnumConst.FighterAttributeEnum.HP],attup[EnumConst.FighterAttributeEnum.HP],self.attrHPCtrl)
    self.attrACKUP.text = attup[EnumConst.FighterAttributeEnum.ATK]+upAddAttr.f_Attribute1[1][2]*self.hero.level +upAddAttr.f_Attribute2[1][2]
    SetCtrl(attbase[EnumConst.FighterAttributeEnum.ATK],attup[EnumConst.FighterAttributeEnum.ATK],self.attrACKCtrl)

    self.attrDEFUP.text = attup[EnumConst.FighterAttributeEnum.DEF] +upAddAttr.f_Attribute1[2][2]*self.hero.level +upAddAttr.f_Attribute2[2][2]
    SetCtrl(attbase[EnumConst.FighterAttributeEnum.DEF],attup[EnumConst.FighterAttributeEnum.DEF],self.attrDEFCtrl)

    --local star2 = ((self.hero.star) * 0.1)
    --self:SetStar(star2,self.qualityFrame_2,self.qualityIcon_2,self.staegeController_2,self.qualityNumIcon_2,self.maxController_2)
    --local star = ((self.hero.star+10) * 0.1)
    --self:SetStar(star,self.qualityFrame,self.qualityIcon,self.staegeController,self.qualityNumIcon,self.maxController)

end
function _M:SetStar(star,qualityFrame,qualityIcon,staegeController,qualityNumIcon,maxController)
    local config = G.dataTable.t_iconframe[tostring(star)]
    local isFrame = config.f_Ornaments ~= ""
    qualityFrame.visible = isFrame
    local atlas = "ui://CharactorUI/"
    if isFrame then
        qualityFrame.url = atlas..config.f_QualityOrnaments
    end
    if config.f_QualityText~= "" then
        qualityIcon.url = atlas..config.f_QualityText
        staegeController.selectedIndex = 1;
    else
        staegeController.selectedIndex = 0;
    end
    qualityNumIcon.url = atlas..config.f_QualityIcon
    if config.f_Id > 10 then
        staegeController.selectedIndex = 0;
        maxController.selectedIndex = star-10;
    else
        maxController.selectedIndex = 0;
    end
end

function _M:OnDestroy()
    UIRedDots.removeViewEvent(PanelNames.UICharactorInfoHeroBreak)

    self.stateController = nil
    self.detailView = nil
    self.resBrekView = nil
    self.break1 = nil
    self.break2 = nil
    self.hasAddRedDots = false;
end

function _M.OnDisable()
    --UIRedDots.removeViewEvent(PanelNames.UICharactorInfoHeroBreak)

end

function _M:SetCtrlSipne(is)
    --if self.ctrlSpine then
    --    if is then
    --        local aniObj = self.fguiObj.displayObject.gameObject.transform:Find("GLoader3D/GoWrapper/zjxg_effect_SkeletonData")
    --        if aniObj then
    --            Util.PlayAction(aniObj.gameObject, "idle", false)
    --        end
    --    end
    --    self.ctrlSpine.visible = is
    --end
end

function _M:OnEnable()
    --UIRedDots.addViewListen(PanelNames.UICharactorInfoHeroBreak,self.fguiObj.gameObjectName..self.btnFetterAward.gameObjectName, self.btnFetterAward,Config.RedDotsType.HeroFetterReward,self.hero["partnerId"]);
    --UIRedDots.addViewListen(PanelNames.UICharactorInfoHeroBreak,self.fguiObj.gameObjectName..self.btnFetterHero.gameObjectName, self.btnFetterHero, Config.RedDotsType.OneHeroFetter,self.hero["partnerId"]);
    --UIRedDots.addViewListen(PanelNames.UICharactorInfoHeroBreak,self.fguiObj.gameObjectName..self.breakbtn.gameObjectName, self.breakbtn, Config.RedDotsType.HeroRank,self.hero["partnerId"]);
    --手动调OnEnable是不合理的
    if self.effectController == nil then
        return
    end
    self.hero.sameNum = ItemManager.getItemCountbyModelId(self.hero.storeId);
    local curSerchID=tonumber(self.hero["partnerModelId"])*1000+self.hero.star
    self.config = G.dataTable["t_herorank"][tostring(curSerchID)]

    if self.config == nil then
        printError("t_herorank not key " , curSerchID)
        return
    end
    self.effectController.selectedIndex = 0;
    if self.config.f_RankUpCost <=self.hero.sameNum then
        self.canBreak=true

    else
        if not logicMgr.ItemManager.getSourceStart("UICharactorInfoHeroBreak") then
            self.effectController.selectedIndex = 1;
        end
        self.canBreak=false
    end

    if self.config.f_HeroStarNext == 0 then
        self.state = 2
    elseif self.hero.star>=80 then
        self.state = 1
    else
        self.state = 0
    end
    self.stateController.selectedIndex = self.state
    local tempStar =logicMgr.HeroManager.starToQuality(self.hero.star)
    self.qualityBreakCtrl.selectedIndex=0
    if self.state == 2 then
        self.qualityBreakCtrl.selectedIndex=1
        self:RefreshBreak(tempStar,self.breakMaxFrame,self.breakMaxIcon,self.breakMaxNumIcon,self.maxStar_Controller_jinjie,self.maxStar_Controller_lr)
        self.bpCtrl.selectedIndex=5
        for i=1,9 do
            self.breakPointCtrls[i].selectedIndex=1
            self.bpEfts[i].visible=false
        end
    else
        if not HelperFunc.IsNull(self.breakCost) then
            self.redbreakCost1.text = ""
            self.redbreakCost2.text = ""
            local costNumStr = getNumString(self.hero.sameNum)
            if  self.hero.sameNum < self.config.f_RankUpCost then
                costNumStr = string.TextColor(costNumStr, "#FF0000");
            end
            self.breakCost.text = costNumStr .. "/" ..self.config.f_RankUpCost
        end
        if self.state==0 then
            self:RefreshBreak(tempStar,self.breakFrame1,self.breakIcon1,self.breakNumIcon1,self.break1Controller_jinjie,self.break1Contrller_max)
            self:RefreshBreak(tempStar+1,self.breakFrame2,self.breakIcon2,self.breakNumIcon2,self.break2Controller_jinjie,self.break2Contrller_max);
        elseif self.state==1 then
            self:RefreshBreak(tempStar,self.breakFrame1,self.breakIcon1,self.breakNumIcon1,self.break1Controller_jinjie,self.break1Contrller_max)
            local nextCfg=G.dataTable["t_herorank"][tostring(self.config.f_HeroStarNext)]
            if nextCfg.f_HeroStar%10~=0 then
                self.qualityBreakCtrl.selectedIndex=1
            else
                self:RefreshBreak(tempStar+1,self.breakFrame2,self.breakIcon2,self.breakNumIcon2,self.break2Controller_jinjie,self.break2Contrller_max);
            end
            local ref=self.hero.star%10
            local num=self.config.f_HeroStarLevelNum
            local index=0
            if num==3 then
                index = 0
            elseif num == 4 then
                index = 1
            elseif num==5 then
                index=2
            elseif num==6 then
                index=3
            elseif num==8 then
                index=4
            elseif num==10 then
                index=5
            end
            self.bpCtrl.selectedIndex=index
            self.breakBars[index+1].value=ref/(num-1)*100
            for i=1,9 do
                if i<=ref then
                    self.breakPointCtrls[i].selectedIndex=1
                else
                    self.breakPointCtrls[i].selectedIndex=0
                end
                self.bpEfts[i].visible=false
            end
            if partnerHandler.ShowBreakPointEffect then
                if ref>0 and ref<=9 then
                    self.bpEfts[ref].visible=true
                    Util.PlayAction(self.bpEfts[ref].wrapTarget, "idle", false);
                end
            end
        end
    end
    partnerHandler.ShowBreakPointEffect=false
    self:UpdateAttr()
    self.detailView:Disable()
    self.resBrekView:Disable()
    if logicMgr.HeroManager.isHeroFullyOpen(self.hero["partnerModelId"]) then
        self.btnSource.visible = true;
    else
        self.btnSource.visible = false;
    end
end

function _M:RereshStarMsg(notShowUpdate)
    self:SetCtrlSipne(true)
    self.hero = logicMgr.HeroManager.getHeroDatabyPartnerId(tostring(self.hero.partnerId))
    self.hero.sameNum = self.hero.sameNum or 0

    self:OnEnable()
    print("显示升级成功弹窗=====",Time.realtimeSinceStartup)
    if not notShowUpdate then
        self.resBrekView:Show(self.hero)
        self.showTipCtrl.selectedIndex = 1
    else
        self.resBrekView:Disable()
        self.showTipCtrl.selectedIndex = 0

    end
end

function _M:RefreshBreak(quality, frame, icon, numIcon, controller1, controller2)
    local config = G.dataTable.t_iconframe[tostring(quality)]
    local isFrame = config.f_Ornaments ~= ""
    frame.visible = isFrame
    if isFrame then
        self:SetIcon(frame,self.ATLAS..config.f_QualityOrnaments,0)
    end

    if config.f_QualityText~= "" then
        self:SetIcon(icon,self.ATLAS..config.f_QualityText,0)
        controller1.selectedIndex = 1;
    else
        controller1.selectedIndex = 0;
    end
    self:SetIcon(numIcon,self.ATLAS..config.f_QualityIcon,0)
    if config.f_Id > 10 then
        controller1.selectedIndex = 0;
        controller2.selectedIndex = config.f_Id - 10;
    else
        controller2.selectedIndex = 0;
    end
end

--- 道具改变事件
--- @private
function _M:OnItemChanged()
    -- 重新拿一次数量
    local newNum = ItemManager.getItemCountbyModelId(self.hero.storeId);
    if newNum ~= self.hero.sameNum then
        self:OnEnable()
    end
    self:updateSource()
end

function _M:OnClickDetail()
    self.detailView:Show(self.hero)
end

function _M:OnClickSendBreak()
    if self.state == 2 then
        UISysTips.AddMsg(getLanguage("Sys_HeroFullRank"))
        return;
    end

    if not self.canBreak then
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips19", nil, "%s"), logicMgr.ItemManager.GetItemName(self.hero.storeId)));
        return
    end

    self:SetCtrlSipne(false)
    local _sameNum = ItemManager.getItemCountbyModelId(self.hero.storeId)
    partnerHandler.sendUpStarMessage(self.hero.partnerId,_sameNum)
    -- 英雄-突破
    if self.breakAudioName then
        AudioManager.Stop(self.breakAudioName);
        self.breakAudioName = nil;
    end
    self.breakAudioName = AudioManager.Play(2012)
    -- 英雄-突破
    --AudioManager.Play(2012)
end

function _M:OnClickFetterHero()
    showUI(PanelNames.UIFetterDetial, self.hero["partnerModelId"])
end

function _M:OnClickFetterAward()
    showUI(PanelNames.UIFetterAward,self.hero["partnerModelId"])
end

function _M:OnClickFetterAttr()
    showUI(PanelNames.UIFetterInfluence)
end

function _M:OnClickGo()
    showUI(PanelNames.UISource, function ()
        if self.goFunc then
            self.goFunc();
        end
    end, self.hero.storeId);
end

function _M:refreshShop()
    self.btnShop.visible = false;
    local actState = logicMgr.CostManager.getFastConsumption();
    if actState == 0 or (actState == 1 and logicMgr.CostManager.isFastConsumptionItems(4, self.hero["partnerModelId"])) then
        if not self.hasAddRedDots and actState == 0 then
            self.hasAddRedDots = true;
            UIRedDots.addViewListen(PanelNames.UICharactorInfoHeroBreak,self.fguiObj.gameObjectName..self.btnShop.gameObjectName, self.btnShop,Config.RedDotsType.CostGiftLink);
        end
        self.btnShop.visible = true;
    end
end

function _M:onClickShop()
    showUI(PanelResNames.UIGiftLink, 4, self.hero["partnerModelId"], function()
        self:OnItemChanged();
    end);
end

function _M:onClickSource()
    --showUI(PanelNames.UISource, function ()
    --    if self.goFunc then
    --        self.goFunc();
    --    end
    --end, self.hero.storeId);
    if not logicMgr.HeroManager.isHeroFullyOpen(self.hero["partnerModelId"]) then
        return;
    end
    self.showSourceController.selectedIndex = 1;
    self.showSourceList = {self.hero.storeId}
    logicMgr.ItemManager.setSourceStart("UICharactorInfoHeroBreak", true);
    self.effectController.selectedIndex = 0;
    self:updateSource();
end

function _M:updateSource()
    logicMgr.ItemManager.updateSourceUI(self.sourceUIobj, self.showSourceList, function ()
        self.showSourceController.selectedIndex = 0;
    end, function ()
        self.showSourceController.selectedIndex = 0;
        if self.goFunc then
            self.goFunc();
        end
    end );
end

return _M